package com.engine.zhlx.financemoduel.workflow.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.webservices.WorkflowServiceImpl;
import weaver.workflow.workflow.WorkflowComInfo;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dusongsong
 * @date 2023年05月12日 14:20
 */
public class WfUtil extends BaseBean {

    /**
     * 校验参数
     *
     * @param paramsJson
     * @return
     */
    public Map<String, Object> checkReqParams(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String formId = Util.null2String(paramsJson.getString("workflowId"));
        String requestName = Util.null2String(paramsJson.getString("requestName"));
        String mainData = Util.null2String(paramsJson.getString("mainData"));
        String detailData = Util.null2String(paramsJson.getString("detailData"));
        String isnextFlow = Util.null2String(paramsJson.getString("isnextFlow"));
        String workcode = Util.null2String(paramsJson.getString("workcode"));
        String code = "SUCCESS";
        String message = "";
        if ("".equals(getWorkflowid(formId))) {
            code = "PARAM_ERROR";
            message += "workflowId参数为空或OA不存在;";
        }
        if ("".equals(Util.null2String(requestName))) {
            code = "PARAM_ERROR";
            message += "requestName参数必填;";
        }
        if (!"".equals(detailData) && !isJSONArray(detailData)) {
            code = "PARAM_ERROR";
            message += "detailData参数JSON格式化错误;";
        }
        if ("".equals(mainData) || !isJSONArray(mainData)) {
            code = "PARAM_ERROR";
            message += "mainData参数为空或JSON格式化错误;";
        }
        if ("".equals(Util.null2String(isnextFlow))) {
            code = "PARAM_ERROR";
            message += "isnextFlow参数为空;";
        }
        if ("".equals(workcode) || "".equals(getResourceid(workcode))) {
            code = "PARAM_ERROR";
            message += "workcode参数为空或OA不存在;";
        }
        apidatas.put("code", code);
        apidatas.put("message", message);
        return apidatas;
    }

    /**
     * 校验参数
     *
     * @param paramsJson
     * @return
     */
    public String checkUpdateParams(JSONObject paramsJson) {
        String formId = Util.null2String(paramsJson.getString("workflowId"));
        String requestId = Util.null2String(paramsJson.getString("requestId"));
        String mainData = Util.null2String(paramsJson.getString("mainData"));
        String detailData = Util.null2String(paramsJson.getString("detailData"));
        String workCode = Util.null2String(paramsJson.getString("workCode"));
        if ("".equals(Util.null2String(getWorkflowid(formId)))) {
            return formId + "不存在，请检查参数:workflowId";
        }
        if ("".equals(Util.null2String(getIdByRequestId(formId, requestId)))) {
            return requestId + "不存在，请检查参数:requestId";
        }
        if ("".equals(Util.null2String(getResourceid(workCode)))) {
            return workCode + "不存在，请检查参数:workCode";
        }
        if (!"".equals(detailData) && !isJSONArray(detailData)) {
            return "JSON格式化错误，请检查参数:detailData";
        }
        if ("".equals(Util.null2String(isJSONArray(mainData)))) {
            return "JSON格式化错误，请检查参数:mainData";
        }
        return "SUCCESS";
    }

    /**
     * 提交流程
     */
    public String submitWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.submitWorkflowRequest(null, requestid, userid, "submit", "由外部调用提交完成");
    }

    /**
     * 删除流程
     */
    public boolean deleteWorkflow(int requestid, int userid) {
        WorkflowServiceImpl serviceImpl = new WorkflowServiceImpl();
        return serviceImpl.deleteRequest(Util.getIntValue(requestid), Util.getIntValue(userid));
    }

    /**
     * @param @param  creatorId    创建人Id
     * @param @param  workflowId   流程Id
     * @param @param  requestName  请求标题
     * @param @param  IsNextFlow   是否提交到下一节点
     * @param @param  requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: WorkflowCreateByMainTableMap
     */
    public String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, Object> requestMainMap) {
        writeLog("-----创建流程传递的参数个数--------");
        writeLog("creatorId:" + creatorId);
        writeLog("workflowId:" + workflowId);
        writeLog("requestName:" + requestName);
        writeLog("IsNextFlow:" + IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);//创建人Id
        requestInfo.setWorkflowid(workflowId);//工作流Id
        requestInfo.setDescription(requestName);//请求标题
        if ("0".equals(IsNextFlow)) {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, Object> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue());
            p++;
        }
        writeLog("-----创建流程传递的参数个数p=" + p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);//创建请求id
            } catch (Exception e) {
                writeLog("=======" + e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:" + requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            writeLog(sbf.toString());
            System.out.println("" + sbf.toString());
        } catch (Exception e) {
            writeLog("错误：" + e);
            System.out.println("错误：" + e);
        }
        return requestid;
    }

    /**
     * 更新主表表单信息
     */
    public boolean updateMainData(String tablename, String requestid, Map<String, Object> map) {
        RecordSet rs = new RecordSet();
        //遍历数据 进行update
        String updatesql = "update " + tablename + " set ";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            updatesql += key + "='" + map.get(key).toString() + "',";
        }
        if (updatesql.endsWith(",")) {
            updatesql = updatesql.substring(0, updatesql.length() - 1);
            updatesql += " where requestid=" + requestid;
        }
        writeLog(">>>>>updateMainData>>>>updatesql=" + updatesql);
        return rs.executeUpdate(updatesql);
    }

    /**
     * 删除明细表数据
     */
    public boolean deleteDetailData(String tableName, String mainid) {
        RecordSet rs = new RecordSet();
        return rs.executeUpdate("delete from  " + tableName + " where mainid=?", mainid);
    }

    /**
     * 更新明细表单信息
     */
    public boolean updateDetailData(String tablename, Map<String, Object> map) {
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (map.get(key) == null || "".equals(map.get(key).toString())) {
                continue;
            }
            keyString += key + ",";
            valueString += "'" + map.get(key).toString() + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        writeLog(">>>>>updateDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 获取表单ID
     */
    public String getWorkflowid(String formid) {
        RecordSet rs = new RecordSet();
        String workflowid = "";
        rs.executeQuery("select id,activeversionid from workflow_base where abs(formid)=?", formid);
        while (rs.next()) {
            String id = Util.null2String(rs.getString("id"));
            String activeversionid = Util.null2String(rs.getString("activeversionid"));
            workflowid = "".equals(activeversionid) ? id : activeversionid;
        }
        return workflowid;
    }

    /**
     * 获取明细主键ID
     */
    public String getIdByRequestId(String formid, String requestid) {
        RecordSet rs = new RecordSet();
        String tableName = "formtable_main_" + formid;
        rs.executeQuery("select id from " + tableName + " where requestid=?", requestid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 获取人员ID
     */
    public String getResourceid(String workcode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from  hrmresource where workcode=?", workcode);
        rs.next();
        return Util.null2String(rs.getString(1));
    }

    /**
     * 获取附件上传目录ID
     */
    public int getDoccategory(String formid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select replace(doccategory,',','') from workflow_base where abs(formid)=?", formid);
        rs.next();
        return Util.getIntValue(rs.getString(1), -1);
    }

    public boolean updateFj(String formid, String requestid, int docid) {
        RecordSet rs = new RecordSet();
        String sql = "update formtable_main_" + formid + " set fj=? where requestid=?";
        return rs.executeUpdate(sql, docid, requestid);
    }

    public boolean isJSONArray(String fieldvalue) {
        boolean flag = false;
        if (!(fieldvalue.trim().equals(""))) {
            try {
                JSONArray.parseArray(fieldvalue);
                flag = true;
            } catch (Exception e) {
                flag = false;
            }
        }
        return flag;
    }

    public String deleteFileByName(String filePath) {
        // 创建 File 对象
        File file = new File(filePath);
        String message = "";
        try {
            // 检查文件是否存在
            if (file.exists()) {
                // 尝试删除文件
                boolean isDeleted = file.delete();
                if (isDeleted) {
                    message = "文件删除成功";
                } else {
                    message = "文件删除失败";
                }
            } else {
                message = "文件不存在";
            }
        } catch (Exception e) {
            message = "发生错误";
            e.printStackTrace();
        }
        return message;
    }

    // 检查文件夹是否存在
    public String getFileName(String filePath){
        Path path = Paths.get(filePath);
        Path fileName = path.getFileName();
        return Util.null2String(fileName);
    }
}
